<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="2">
        <div class="head-container">
          <el-input
            v-model="flatName"
            placeholder="请输入小区名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="threeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="tid"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="16">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="层数" prop="floors">
            <el-input
              v-model="queryParams.floors"
              placeholder="请输入层数"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="房间号" prop="roomNumber">
            <el-input
              v-model="queryParams.roomNumber"
              placeholder="请输入房间号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="户型" prop="capacity">
            <el-select v-model="queryParams.capacity" placeholder="请选择户型" clearable>
              <el-option
                v-for="dict in dict.type.house_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['room:apartment:add']"
            >
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['room:apartment:edit']"
            >
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['room:apartment:remove']"
            >
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['room:apartment:export']"
            >
              导出
            </el-button>
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="apartmentList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" type="index" />
          <el-table-column label="地址" align="center" prop="address" />
          <el-table-column label="户型" align="center" prop="capacity">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.house_type" :value="scope.row.capacity" />
            </template>
          </el-table-column>
          <el-table-column label="平方米" align="center" prop="squareMeter" />
          <el-table-column label="评估单价(元/m²)" align="center" prop="evaluationPrice" />
          <!-- <el-table-column label="评估总价(元/m²)" align="center" prop="evaluateTheTotalPrice" /> -->
          <el-table-column label="图片" align="center" prop="picture">
            <template slot-scope="scope">
              <image-preview :src="scope.row.picture" :width="50" :height="50" />
            </template>
          </el-table-column>
          <el-table-column label="是否出租" align="center" prop="availability">
            <template slot-scope="scope">
              <!-- <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.availability" /> -->
              <el-tag
                :type="
                  setYN(scope.row.availability, dict.type.sys_yes_no).label == '是'
                    ? 'danger'
                    : 'success'
                "
              >
                {{
                  setYN(scope.row.availability, dict.type.sys_yes_no).label == '是'
                    ? '已出租'
                    : '未出租'
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleUpdate(scope.row, 2)"
                v-hasPermi="['room:apartment:see']"
              >
                查看
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row, 3)"
                v-hasPermi="['room:apartment:edit']"
              >
                修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['room:apartment:remove']"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
      <el-col :span="6">
        <div class="head-container">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <div>展示图</div>
              <div class="cardTip">绿色:待租,红色:已租,灰色:未登记</div>
            </div>
            <div>
              <div class="showBox" v-for="(item, index) in showBox.vertical" :key="index">
                <div class="showBoxRow">
                  <div
                    class="showBoxItem"
                    :class="[setRoomStatus(item + '-' + setRoomNum(citem))]"
                    :style="{ width: setWidth(showBox.line) }"
                    v-for="(citem, cindex) in showBox.line"
                    :key="cindex"
                  >
                    {{ item }}-{{ setRoomNum(citem) }}
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改公寓对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="flexForm"
        :disabled="openType == 2"
      >
        <el-form-item label="小区" prop="houseId" class="w50">
          <el-select
            v-model="form.houseId"
            placeholder="请选择小区"
            @change="houseChange"
            :disabled="openType == 3"
          >
            <el-option
              v-for="item in houseList"
              :key="item.houseId"
              :label="item.title"
              :value="item.houseId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋信息" prop="buildingId" class="w50">
          <el-select
            v-model="form.buildingId"
            placeholder="请选择楼栋信息"
            :disabled="openType == 3"
          >
            <el-option
              v-for="item in buildingList"
              :key="item.buildingId"
              :label="item.buildingName"
              :value="item.buildingId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否出租" prop="availability" v-if="openType != 1" class="w50">
          <el-radio-group v-model="form.availability" disabled>
            <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="层数" prop="floors" class="w50">
          <el-input v-model="form.floors" placeholder="请输入层数" :disabled="openType == 3" />
        </el-form-item>
        <el-form-item label="房间号" prop="roomNumber" class="w50">
          <el-input
            v-model="form.roomNumber"
            placeholder="请输入房间号"
            :disabled="openType == 3"
          />
        </el-form-item>

        <el-form-item label="户型" prop="capacity" class="w50">
          <el-select
            v-model="form.capacity"
            placeholder="请选择户型"
            clearable
            :disabled="openType == 3"
          >
            <el-option
              v-for="dict in dict.type.house_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="平方米" prop="squareMeter" class="w50">
          <el-input-number
            v-model="form.squareMeter"
            controls-position="right"
            :min="1"
            placeholder="请输入平方米"
            @blur="setPrice"
          />
        </el-form-item>
        <el-form-item label="评估单价(元/m²/月)" prop="evaluationPrice" class="w50">
          <el-input-number
            v-model="form.evaluationPrice"
            controls-position="right"
            :min="1"
            placeholder="请输入评估单价"
            @blur="setPrice"
          />
        </el-form-item>
        <el-form-item label="评估总价(元/年)" prop="evaluateTheTotalPrice" class="w50">
          <el-input-number
            v-model="form.evaluateTheTotalPrice"
            controls-position="right"
            :min="1"
            placeholder="请输入评估总价"
            disabled
          />
        </el-form-item>
        <el-form-item label="图片" prop="picture" class="w100">
          <!-- <file-upload v-model="form.attachment1" /> -->
          <image-upload :dis="openType == 2 || openType == 3" v-model="form.picture" />
        </el-form-item>
        <el-form-item label="视频" prop="video" class="w100">
          <file-upload
            :fileType="['mp4', 'avi', 'wmv']"
            v-model="form.video"
            :dis="openType == 2 || openType == 3"
            :limit="2"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="openType != 2">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listApartment,
  getApartment,
  delApartment,
  addApartment,
  updateApartment
} from '@/api/room/apartment'
import { listHouse, treeHouse } from '@/api/room/house'
import { listBuilding } from '@/api/room/building'
export default {
  name: 'Apartment',
  dicts: ['sys_yes_no', 'house_type'],
  data() {
    return {
      openType: 1,
      flatName: '',
      threeOptions: undefined,
      defaultProps: {
        children: 'childList'
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      houseList: [],
      buildingList: [],
      // 公寓表格数据
      apartmentList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        buildingId: '',
        pageSize: 10,
        apartmentName: null,
        houseId: null,
        buildingId: null,
        floors: null,
        roomNumber: null,
        capacity: null,
        rent: null,
        availability: null,
        attachment: null
      },
      showBox: {
        line: 0,
        vertical: 0
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        houseId: [{ required: true, message: '小区不能为空', trigger: 'change' }],
        buildingId: [{ required: true, message: '楼栋不能为空', trigger: 'change' }],
        floors: [{ required: true, message: '层数不能为空', trigger: 'blur' }],
        roomNumber: [{ required: true, message: '房间号不能为空', trigger: 'blur' }],
        capacity: [{ required: true, message: '容纳人数不能为空', trigger: 'blur' }],
        availability: [{ required: true, message: '请选择是否出租', trigger: 'change' }],
        rent: [{ required: true, message: '租金不能为空', trigger: 'change' }],
        squareMeter: [{ required: true, message: '平方米不能为空', trigger: 'blur' }],
        evaluationPrice: [{ required: true, message: '评估单价不能为空', trigger: 'blur' }],
        evaluateTheTotalPrice: [{ required: true, message: '评估总价不能为空', trigger: 'blur' }],
        picture: [{ required: true, message: '图片不能为空', trigger: 'change' }]
        // video: [{ required: true, message: '视频不能为空', trigger: 'change' }]
      },
      dzRooms: [],
      czRooms: []
    }
  },
  created() {
    this.getList()
    this.getHouseList()
    this.getThree()
  },
  methods: {
    setYN(value, arr) {
      return arr.find((item) => {
        if (item.value == value) {
          return item
        }
      })
    },
    setRoomUpload(dataStr, key) {
      if (dataStr) {
        const data = JSON.parse(dataStr)[key]
        return data
      } else {
        return null
      }
    },
    setRoomNum(num) {
      return num < 10 ? '0' + num : num
    },
    setPrice() {
      if (this.form.squareMeter && this.form.evaluationPrice) {
        this.form.evaluateTheTotalPrice = this.form.squareMeter * this.form.evaluationPrice * 12
      }
    },
    setRoomStatus(value) {
      let color = ''
      if (this.dzRooms.indexOf(value) != -1) {
        color = 'dz'
      } else if (this.czRooms.indexOf(value) != -1) {
        color = 'cz'
      }
      console.log(color)
      return color
    },
    setWidth(num) {
      const bfb = 100 / num
      return `calc(${bfb}%)`
    },
    houseChange(value) {
      this.getBuildingList(value)
    },
    /** 查询楼栋列表 */
    getBuildingList(houseId) {
      listBuilding({ houseId }).then((response) => {
        this.buildingList = response.rows
      })
    },
    /** 查询房源列表 */
    getHouseList() {
      listHouse().then((response) => {
        this.houseList = response.rows
      })
    },
    getThree() {
      treeHouse().then((res) => {
        console.log(res)
        res.data.forEach((item) => {
          item.tid = item.houseId
          item.label = item.title
          item.childList.forEach((citem) => {
            citem.label = citem.buildingName
            citem.tid = citem.buildingId
          })
        })
        this.threeOptions = res.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      console.log(data)
      if (data.buildingId) {
        this.showBox.line = data.apartmentsPerFloor
        this.showBox.vertical = data.floors
        this.queryParams.buildingId = data.buildingId
      } else {
        this.queryParams.buildingId = ''
      }
      this.queryParams.houseId = data.houseId
      this.handleQuery()
    },
    /** 查询公寓列表 */
    getList() {
      this.loading = true
      listApartment(this.queryParams).then((response) => {
        this.apartmentList = response.rows
        this.total = response.total
        this.loading = false
        this.czRooms = []
        this.dzRooms = []
        this.apartmentList.forEach((item) => {
          if (item.availability == 'Y') {
            this.czRooms.push(item.floors + '-' + this.setRoomNum(item.roomNumber))
          } else {
            this.dzRooms.push(item.floors + '-' + this.setRoomNum(item.roomNumber))
          }
        })
        console.log(this.czRooms, this.dzRooms)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        apartmentId: null,
        apartmentName: null,
        houseId: null,
        buildingId: null,
        floors: null,
        roomNumber: null,
        capacity: null,
        rent: null,
        availability: null,
        video: null,
        picture: null,
        evaluateTheTotalPrice: null,
        squareMeter: null,
        evaluationPrice: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.apartmentId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.openType = 1
      this.open = true
      this.title = '添加公寓'
    },
    /** 修改按钮操作 */
    handleUpdate(row, openType) {
      this.openType = openType
      this.reset()
      const apartmentId = row.apartmentId || this.ids
      getApartment(apartmentId).then((response) => {
        const data = response.data
        this.form = JSON.parse(JSON.stringify(data))
        this.getBuildingList(response.data.houseId)
        // if (data.attachment) {
        //   const uploadObj = JSON.parse(data.attachment)
        //   this.form.attachment1 = uploadObj.img || []
        //   this.form.attachment2 = uploadObj.video || []
        // } else {
        //   this.form.attachment1 = null
        //   this.form.attachment2 = null
        // }
        this.open = true
        this.title = '修改公寓'
      })
    },
    /** 提交按钮 */
    submitForm() {
      // const formData = JSON.parse(JSON.stringify(this.form))
      // const list = {
      //   img: formData.attachment1,
      //   video: formData.attachment2
      // }
      // formData.attachment = JSON.stringify(list)
      // this.form = formData
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.apartmentId != null) {
            updateApartment(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addApartment(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const apartmentIds = row.apartmentId || this.ids
      this.$modal
        .confirm('是否确认删除公寓为"' + row.apartmentName + '"的数据项？')
        .then(function () {
          return delApartment(apartmentIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'room/apartment/export',
        {
          ...this.queryParams
        },
        `apartment_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
<style lang="scss" scoped>
.w50 {
  width: calc(50% - 50px);
  margin-right: 50px;
}
.cardTip {
  color: #909399;
  margin-top: 10px;
  font-size: 16px;
}
.showBox {
  .showBoxRow {
    display: flex;
    align-items: flex-start;
    margin-bottom: 4px;
    .showBoxItem {
      background-color: #909399;
      color: #fff;
      margin-right: 4px;
      font-size: 1rem;
      min-height: 2rem;
      display: flex;
      align-items: center;
      justify-content: center;
      &.cz {
        background-color: #f56c6c;
      }
      &.dz {
        background-color: #67c23a;
      }
      &:last-of-type {
        margin-right: 0;
      }
    }
  }
}
</style>
